﻿using System.Net;
using System.Net.Sockets;
using Oxage.Models;

namespace Oxage.Drivers
{
	public class UdpConnector : ConnectorBase
	{
		#region Private members
		private UdpClient client;
		private UdpModel model;
		#endregion

		#region Constructor
		public UdpConnector()
		{
			client = new UdpClient();
			model = new UdpModel();

			//Default value
			this.EndPoint = model.EndPoint as IPEndPoint;
		}
		#endregion

		#region Public properties
		/// <summary>
		/// Gets or sets the remote IP address or host name. Value is used on Open() method call.
		/// </summary>
		public IPEndPoint EndPoint
		{
			get;
			set;
		}

		/// <summary>
		/// Gets a value indicating whether a connection is established.
		/// </summary>
		public bool IsConnected
		{
			get
			{
				return (client != null && client.Client != null && client.Client.Connected);
			}
		}
		#endregion

		#region IMachineController Members
		public override string Name
		{
			get { return "UDP"; }
		}

		/// <summary>
		/// Connects to a server.
		/// </summary>
		public override void Open()
		{
			client.Connect(this.EndPoint);
		}

		/// <summary>
		/// Disconnects from a server.
		/// </summary>
		public override void Close()
		{
			client.Close();
		}

		/// <summary>
		/// Sends bytes to the connected server.
		/// </summary>
		/// <param name="data"></param>
		public override void Write(byte[] data)
		{
			client.Send(data, data.Length);
		}
		#endregion
	}
}
